package com.example.sportmeet

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.Editable
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.RadioGroup
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.io.IOException

class EntryActivity : AppCompatActivity() {
    private lateinit var etSno: EditText
    private lateinit var etName: EditText
    private lateinit var rgGender: RadioGroup
    private lateinit var spEvent: Spinner
    private lateinit var tvEvent: TextView
    private lateinit var btnSubmit: Button

    private val maleEvents = arrayOf("100米跑","50米跑", "跳高","跳绳","跳远", "铅球")
    private val femaleEvents = arrayOf("50米跑","三级跳远", "跳高", "标枪","跳绳","铁饼")
    private val selectedEvents = mutableSetOf<String>()

    companion object {
        private const val STORAGE_PERMISSION_CODE = 1001
        private const val MAX_EVENTS = 2
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_entry)

        checkStoragePermission()
        initViews()
        setupGenderRadioGroup()
        setupSpinner()
        setupSnoValidation()
        setupSubmitButton()
    }

    private fun initViews() {
        etSno = findViewById(R.id.etSno)
        etName = findViewById(R.id.etName)
        rgGender = findViewById(R.id.rgGender)
        spEvent = findViewById(R.id.spEvent)
        tvEvent = findViewById(R.id.tvEvent)
        btnSubmit = findViewById(R.id.btnSubmit)
    }

    private fun setupGenderRadioGroup() {
        rgGender.setOnCheckedChangeListener { _, checkedId ->
            val events = if (checkedId == R.id.rbMale) maleEvents else femaleEvents
            updateSpinnerAdapter(events)

            // Clear selected events when gender changes
            if (selectedEvents.isNotEmpty()) {
                selectedEvents.clear()
                updateSelectedEvents()
            }
        }

        // Set default to male
        rgGender.check(R.id.rbMale)
    }

    private fun updateSpinnerAdapter(events: Array<String>) {
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, events)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spEvent.adapter = adapter
    }

    private fun setupSpinner() {
        // Initial setup with male events
        updateSpinnerAdapter(maleEvents)

        spEvent.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
                val selected = parent.getItemAtPosition(position).toString()
                handleEventSelection(selected)
            }

            override fun onNothingSelected(parent: AdapterView<*>) {}
        }
    }

    private fun handleEventSelection(selected: String) {
        when {
            selectedEvents.size >= MAX_EVENTS -> {
                Toast.makeText(
                    this@EntryActivity,
                    "最多只能选择 $MAX_EVENTS 个项目",
                    Toast.LENGTH_SHORT
                ).show()
            }
            selected in selectedEvents -> {
                Toast.makeText(
                    this@EntryActivity,
                    "已选择该项目",
                    Toast.LENGTH_SHORT
                ).show()
            }
            else -> {
                selectedEvents.add(selected)
                updateSelectedEvents()
            }
        }
    }

    private fun setupSnoValidation() {
        etSno.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable) {
                if (s.toString().isNotEmpty() && checkDuplicateSno(s.toString())) {
                    Toast.makeText(
                        this@EntryActivity,
                        "该学号已报名，请勿重复报名",
                        Toast.LENGTH_SHORT
                    ).show()
                    etSno.error = "学号重复"
                } else {
                    etSno.error = null
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
        })
    }

    private fun setupSubmitButton() {
        btnSubmit.setOnClickListener {
            if (validateForm()) {
                submitForm()
            }
        }
    }

    private fun validateForm(): Boolean {
        if (etSno.text.isBlank()) {
            etSno.error = "请输入学号"
            etSno.requestFocus()
            return false
        }

        if (etSno.text.length != 10) { // 假设学号长度为10
            etSno.error = "学号必须为10位"
            etSno.requestFocus()
            return false
        }

        if (etName.text.isBlank()) {
            etName.error = "请输入姓名"
            etName.requestFocus()
            return false
        }

        if (selectedEvents.isEmpty()) {
            Toast.makeText(this, "请至少选择一个项目", Toast.LENGTH_SHORT).show()
            return false
        }

        return true
    }

    private fun checkDuplicateSno(sno: String): Boolean {
        if (!hasStoragePermission()) {
            requestStoragePermission()
            return false
        }

        val file = File(getExternalFilesDir(null), "Sno.txt")
        if (!file.exists()) return false

        return try {
            BufferedReader(FileReader(file)).use { reader ->
                reader.lineSequence().any { it.trim() == sno.trim() }
            }
        } catch (e: IOException) {
            e.printStackTrace()
            false
        }
    }

    private fun updateSelectedEvents() {
        tvEvent.text = selectedEvents.joinToString("\n") {
            "• $it" // 添加项目符号使列表更清晰
        }
    }

    private fun submitForm() {
        val sno = etSno.text.toString().trim()
        val name = etName.text.toString().trim()
        val gender = if (rgGender.checkedRadioButtonId == R.id.rbMale) "男" else "女"

        if (saveToFiles(sno, name, gender)) {
            clearForm()
            Toast.makeText(this, "报名成功", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "保存失败，请重试", Toast.LENGTH_SHORT).show()
        }
    }

    private fun saveToFiles(sno: String, name: String, gender: String): Boolean {
        if (!hasStoragePermission()) {
            requestStoragePermission()
            return false
        }

        val snoFile = File(getExternalFilesDir(null), "Sno.txt")
        val submitFile = File(getExternalFilesDir(null), "Submit.txt")

        try {
            // Save to Sno.txt
            FileWriter(snoFile, true).use { writer ->
                writer.write("$sno\n")
            }

            // Save to Submit.txt
            val eventInfo = mapOf(
                "学号" to sno,
                "姓名" to name,
                "性别" to gender,
                "项目" to selectedEvents.joinToString(";")
            )
            val formattedInfo = eventInfo.entries.joinToString(",") { "${it.key}:${it.value}" }

            FileWriter(submitFile, true).use { writer ->
                writer.write("$formattedInfo\n")
            }

            return true
        } catch (e: IOException) {
            e.printStackTrace()
            return false
        }
    }

    private fun clearForm() {
        etSno.text.clear()
        etName.text.clear()
        selectedEvents.clear()
        tvEvent.text = ""
        rgGender.check(R.id.rbMale) // 重置为默认性别
        spEvent.setSelection(0)
        etSno.requestFocus()
    }

    // Storage permission handling
    private fun checkStoragePermission() {
        if (!hasStoragePermission()) {
            requestStoragePermission()
        }
    }

    private fun hasStoragePermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun requestStoragePermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ),
            STORAGE_PERMISSION_CODE
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            STORAGE_PERMISSION_CODE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission granted
                } else {
                    Toast.makeText(
                        this,
                        "需要存储权限才能保存报名信息",
                        Toast.LENGTH_LONG
                    ).show()
                }
            }
        }
    }

    // Menu handling
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.entry, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.menu_exit -> {
                showExitDialog()
                true
            }
            R.id.menu_cancel -> {
                clearForm()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun showExitDialog() {
        AlertDialog.Builder(this)
            .setTitle("退出确认")
            .setMessage("确定要退出报名系统吗？")
            .setPositiveButton("确定") { _, _ -> finish() }
            .setNegativeButton("取消", null)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show()
    }
}